import router from "@/router";
import store from "@/store";
import moment from "moment";

import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

import {
    getToken,
    removeToken
} from '@/utils/auth'
import Vue from 'vue'
let that = Vue.prototype

import {
    Loading,
    Message,
    MessageBox
} from "element-ui";
let $loading = "";
const recursion = (list, val) => {
    let str = false;
    for (let v of list) {
        // console.log(v.path,"%%%",val);
        if (v.path == val) {
            str = true;
            break;
        } else if (!str) {
            str = recursion(v.child, val);
        }
    }
    // console.log("QWQ",str);
    return str;
};
export default {
    /**
     * http://ywk.willmid.cn/       测试
     * https://api.yiweika.net/     线上
     */
    data: {
        // baseURL: "http://ywk.willmid.cn/",
        baseURL: 'https://api.yiweika.net/',
        userChange: {
            realname: '姓名',
            phone: "手机号码",
            username: "名称",
            // avatar:"头像",
            gender: '性别',
            birthday: '生日',
            vip_id: '会员等级',
            about: '左右',
            around: '前后',
            header: '头围',
            address: '地址',
            remarks: '备注',
        }
    },
    textfile(val, key, vipList) {
        if (key == 'vip_id') {
            return vipList.find(v => v.id == val).title
        }
        if (key == 'gender') {//0 保密 1 男 2 女 -1条件限制
            return ['保密', '男', '女'][val] || '条件限制'
        }
        return !val ? '空' : val;
    },
    copyValue(val) {
        const input = document.createElement("input");
        document.body.appendChild(input);
        input.setAttribute("value", val);
        input.select();
        if (document.execCommand("copy")) {
            document.execCommand("copy");
            Message.success("已复制到剪贴板");
        }
        document.body.removeChild(input);
    },
    downloadXlsx(blob, name = "") {//下载 表格.xlsx
        if (!blob) return;
        var reader = new FileReader()
        reader.addEventListener('loadend', (e) => {
            console.log(blob.type, 'blob.type', e);
            // if(blob.type === 'application/json'){
            try {
                let { code, msg } = JSON.parse(e.target.result);
                Message.error(msg);
                return;
            } catch (error) {
                var downloadUrl = window.URL.createObjectURL(new Blob([blob]));//转换
                var anchor = document.createElement("a");
                anchor.href = downloadUrl;
                // 生成时间戳
                let date = new Date();
                let timestamp = this.time(date, true);
                anchor.download = decodeURI(name + timestamp + '.xls');
                anchor.click();
            }
        })
        reader.readAsText(blob)
    },
    typeTitle(val, title = "") {
        switch (Number(val)) {
            case 1:
                val = title + "详情";
                break;
            case 2:
                val = "新增" + title;
                break;
            case 3:
                val = "编辑" + title;
                break;
        }
        return val;
    },
    goUrl: url => {
        if (url) {
            router.push({
                path: url
            });
        } else {
            that.$message.error("路由参数错误");
        }
    },
    goNew(url) {
        if (!url || url == "#") return;
        window.open(url);
    },
    backPage(index = -1) {
        router.go(index);
    },
    jurisdictionJudge(val) {
        let menuList = store.state.settings.menuList;
        // let path = thas.$route.path,str=false;
        console.log(recursion, "@#!@$@");
        return recursion(menuList, val);
    },
    messageBox(message) {
        return new Promise(req => {
            MessageBox({
                title: "提示",
                message,
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                beforeClose: (action, instance, done) => {
                    req({
                        action,
                        instance,
                        done
                    });
                },
            })
                .then(action => { })
                .catch(() => {
                    req({
                        action: false
                    });
                });
        });
    },
    isLoadding(flag) {
        if (flag) {
            Loading.service({
                fullscreen: true
            });
        } else {
            Loading.service({
                fullscreen: true
            }).close();
        }
    },
    productNameFiltering({ goods = {} }) {
        let str = '';
        switch (goods?.type) {
            case 4://洗护
                str = `${goods?.title} ${goods?.details}`;
                break;
            default:
                str += goods.title;
                let keys = ['itemInfo', 'roughcastInfo', 'needleInfo', 'sizeInfo', 'lengthInfo', 'sexInfo', 'colourInfo'];
                for (let key of keys) {
                    if (goods[key]) {
                        str += ' ' + goods[key].title || ''
                    }
                }
                break;
        }
        return str;
        // return goods.type==2?`${goods.title} ${goods.sku_text}`:`${goods.series_name} ${goods.blank_type_name} ${goods.needle_type_name} ${goods.size_name} ${goods.length_name} ${goods.sex_name} ${goods.colour_name}`
    },
    downloadXlsx(blob, name = "") { //下载 表格.xlsx
        if (!blob) return;
        var reader = new FileReader()
        reader.addEventListener('loadend', (e) => {
            console.log(blob.type, 'blob.type', e);
            // if(blob.type === 'application/json'){
            try {
                let {
                    code,
                    msg
                } = JSON.parse(e.target.result);
                Message.error(msg);
                return;
            } catch (error) {
                var downloadUrl = window.URL.createObjectURL(new Blob([blob])); //转换
                var anchor = document.createElement("a");
                anchor.href = downloadUrl;
                // 生成时间戳
                let date = new Date();
                let timestamp = this.time(date, true);
                anchor.download = decodeURI(name + timestamp + '.xls');
                anchor.click();
            }
        })
        reader.readAsText(blob)
    },
    /**
     * 条件运算 例如: a?.b?.c
     * 使用方法  {{utils.useOptionChain(obj,'a.b.c')}}
     *
    */
    useOptionChain(obj, keyName = '') {
        if (!obj) return null
        let keys = (keyName + '').split('.')
        let tempObj = obj
        for (let i = 0; i < keys.length; i++) {
            if (!tempObj) return
            if (keys[i] !== '') {
                let index = keys[i].indexOf('[');
                if (index !== -1) {
                    let str = keys[i].slice(0, index)
                    tempObj = tempObj?.[str]?.[this.getParenthesesStr(keys[i])]
                } else tempObj = tempObj?.[keys[i]]
            }
        }
        return tempObj
    },
    /**
     * 取出小括号内的内容
     * @param text
     * @returns {string}
     */
    getParenthesesStr(str) {
        let list = [];
        if (str.indexOf("[") != -1 && str.indexOf("]") != -1) {
            let a1 = /\[(.+?)\]/g                 //正则获取小括号
            list = str.match(a1);    //因为输出的是数组
            for (let i in list) {
                list[i] = list[i].replace("[", "");         //用空字符替换掉括号
                list[i] = list[i].replace("]", "");
            }
        }
        return list;
    },
    message(message, type = "suc") {
        switch (type) {
            case "suc":
                Message({
                    showClose: true,
                    message,
                    type: "success"
                });
                break;
            case "war":
                Message({
                    showClose: true,
                    message,
                    type: "warning"
                });
                break;
            case "err":
                Message({
                    showClose: true,
                    message,
                    type: "error"
                });
                break;
            case "info":
                Message({
                    showClose: true,
                    message,
                    type: "info"
                });
                break;
        }
    },
    //会员来源
    sourceTxt(val) {
        switch (+val) {
            case 8:
                val = "老系统数据";
                break;
            case 1:
                val = "朋友推荐";
                break;
            case 2:
                val = "老顾客推荐";
                break;
            case 3:
                val = "顾客来店";
                break;
            case 4:
                val = "其他";
                break;
            case 5:
                val = "小程序";
                break;
            case 6:
                val = "抖音";
                break;
            case 7:
                val = "美团";
                break;
        }
        return val;
    },
    /**
     * @param {Object} arr 数组
     * @param {Object} name 字段名
     * 数组提取某个元素名并拼接成一个新数组返回
     */
    arrGetName(arr, owName, str) {
        if (arr.length > 0) {
            var newArr = [];
            arr.forEach((a, i) => {
                newArr.push(a[owName]);
            });
            if (str != "") {
                newArr = newArr.join(str);
            }
            return newArr;
        } else {
            return false;
        }
    },
    /**
     * @param {Object} arr 数组
     * @param {Object} newArrLength 要拆分的每个数量
     * 数组拆分
     */
    changeArrGroup(arr, newArrLength) {
        let changeIndex = 0;
        let secondArr = [];
        while (changeIndex < arr.length) {
            secondArr.push(arr.slice(changeIndex, (changeIndex += newArrLength)));
        }
        return secondArr;
    },
    //key(需要检索的键） url（传入的需要分割的url地址，例：?id=2&age=18）
    getSearch(key, Url) {
        var str = Url;
        str = str.substring(1, str.length); // 获取URL中?之后的字符（去掉第一位的问号）
        // 以&分隔字符串，获得类似name=xiaoli这样的元素数组
        var arr = str.split("&");
        var obj = new Object();
        // 将每一个数组元素以=分隔并赋给obj对象
        for (var i = 0; i < arr.length; i++) {
            var tmp_arr = arr[i].split("=");
            obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);
        }
        return obj[key];
    },
    /**
     * 判断是否是微信环境
     */
    isWX() {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
            return true;
        }
        return false;
    },
    /**
     * @param [{Object}] 数组对象
     * @param {String} str 给定字符
     * 对象中的null或者空字符串转换为 给定的字符
     */
    objNull2String(arr, str = "-") {
        if (arr.length > 0) {
            var resArr = [];
            arr.forEach((a, i) => {
                let resParams = {};
                Object.keys(a).forEach(key => {
                    if (a[key] === "" || a[key] === null) {
                        //判断参数不为空字符串
                        resParams[key] = str;
                    } else {
                        resParams[key] = a[key];
                    }
                });
                resArr.push(resParams);
            });
            console.log(resArr);
            return resArr;
        }
        return arr;
    },
    /**
     * @param {Object} fmt
     * @param {Object} date
     * 时间格式化
     */
    dateFormat(fmt, date) {
        if (date instanceof Date && !isNaN(date.getTime())) {
            let ret;
            let opt = {
                "Y+": date.getFullYear().toString(), // 年
                "m+": (date.getMonth() + 1).toString(), // 月
                "d+": date.getDate().toString(), // 日
                "H+": date.getHours().toString(), // 时
                "M+": date.getMinutes().toString(), // 分
                "S+": date.getSeconds().toString(), // 秒
            };
            for (let k in opt) {
                ret = new RegExp("(" + k + ")").exec(fmt);
                if (ret) {
                    fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0"));
                }
            }
            console.log(111111111111);
            return fmt;
        } else {
            console.log(222222222222);
            return "-";
        }
    },
    /**--------------获取cookies--------------**/
    getCookie(name) {
        let arr,
            reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if ((arr = document.cookie.match(reg))) return arr[2];
        else return null;
    },
    time(date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? "0" + m : m;
        var d = date.getDate();
        d = d < 10 ? "0" + d : d;
        var h = date.getHours();
        h = h < 10 ? "0" + h : h;
        var minute = date.getMinutes();
        minute = minute < 10 ? "0" + minute : minute;
        var second = date.getSeconds();
        second = second < 10 ? "0" + second : second;
        // return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
        return y + "-" + m + "-" + d;
    },
    //返回是否是店长
    getIsShopowner() {
        let type = store.state.user?.userInfo?.position?.id;
        return type === 6 || type === 4;
    },
    timeMonth(date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? "0" + m : m;
        var d = date.getDate();
        d = d < 10 ? "0" + d : d;
        var h = date.getHours();
        h = h < 10 ? "0" + h : h;
        var minute = date.getMinutes();
        minute = minute < 10 ? "0" + minute : minute;
        var second = date.getSeconds();
        second = second < 10 ? "0" + second : second;
        // return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
        return y + "-" + m;
    },
    /**--------------设置cookies--------------**/
    setCookie(c_name, value, expiredays) {
        let exdate = new Date();
        exdate.setDate(exdate.getDate() + expiredays);
        document.cookie = c_name + "=" + value + (expiredays == null ? "" : ";expires=" + exdate.toGMTString());
    },

    /**--------------删除cookies--------------**/
    delCookie(name) {
        let exp = new Date();
        exp.setTime(exp.getTime() - 1);
        let cval = getCookie(name);
        if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
    },

    /**--------------sessionStorage获取对象--------------**/
    getSession(key, isObj = true) {
        let value = sessionStorage.getItem(key);
        if (isObj) {
            value = JSON.parse(value);
        }
        return value;
    },

    /**--------------sessionStorage设置对象--------------**/
    setSession(key, value) {
        let str = value;
        if (value !== undefined && typeof value === "object") {
            str = JSON.stringify(value);
        }
        sessionStorage.setItem(key, str);
    },

    /**--------------sessionStorage删除对象--------------**/
    delSession(key) {
        sessionStorage.removeItem(key);
    },

    /*-----------------手机号隐藏中间4位-------------------*/
    hidePhoneNum(phone) {
        let result = "";
        if (phone != null) {
            result = phone.substring(0, 3) + "****" + phone.substring(7);
        }
        return result;
    },

    /*---------------------获取当前最新时间----------------------*/
    getNowDate(date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? "0" + m : m;
        var d = date.getDate();
        d = d < 10 ? "0" + d : d;
        var h = date.getHours();
        h = h < 10 ? "0" + h : h;
        var minute = date.getMinutes();
        minute = minute < 10 ? "0" + minute : minute;
        var second = date.getSeconds();
        second = second < 10 ? "0" + second : second;
        return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
    },

    /**----------------- 数字转换金额------------------ ***/
    numberToAmount(num, n = 2) {
        if (!num && num !== 0) {
            return "";
        }
        if (!isNaN(num)) {
            num = parseFloat(num).toFixed(n);
        } else {
            num = num;
        }
        var re = /(\d{1,3})(?=(\d{3})+(?:\.))/g;
        return num.replace(re, "$1,");
    },

    /**-------------------------- 金额转换数字----------------------**/
    amountToNumber(value) {
        let num = value;
        if (!num) {
            return "";
        }
        num = num.toString();
        num = num.replace(/[ ]/g, "");
        num = num.replace(/,/gi, "");
        if (!isNaN(num)) {
            return Number(num);
        }
        return num;
    },
    /**-------------------------- 字符串转数字且保留两位有效小数----------------------**/
    stringToNumber(val) {
        if (!val) {
            return "";
        }
        val = val.replace(/[ ]/g, "");
        val = val.replace(/,/gi, "");
        if (!isNaN(val)) {
            return parseFloat(val).toFixed(2);
        }
        return val;
    },
    /**--------------检查上传文件的大小--------------**/
    checkFileSize(file, size = 10) {
        if (file.size > size * 1024 * 1024) {
            MessageBox.confirm(`文件大小不能超过${size}MB`, {
                confirmButtonText: "知道了",
                type: "warning",
                showCancelButton: false,
                showClose: false,
            });
            return false;
        }
        return true;
    },
    /**--------------日期转化--------------**/
    dateFormatter(value, fmt = "yyyy-MM-dd hh:mm:ss") {
        if (!value) {
            return "";
        }
        let date = new Date(Number(value));
        let o = {
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "h+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds(), //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            S: date.getMilliseconds(), //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        return fmt;
    },

    /**----------------超出字数显示省略号---------------------------**/
    overPartWord(value) {
        if (!value) {
            return "";
        }
        if (value.length > 10) {
            return value.substring(0, 10) + "...";
        }
        return value;
    },
    /**-------------------对象或数组深拷贝---------------------------**/
    objDeepCopy(source) {
        let sourceCopy = source instanceof Array ? [] : {};
        for (let item in source) {
            sourceCopy[item] = typeof source[item] === "object" && source[item] !== null ? this.objDeepCopy(source[item]) : source[item] === null ? "" : source[item];
        }
        return sourceCopy;
    },
    /**------保留n位小数(直接截取，不会四舍五入)-------**/
    pointTo(num, n = 2) {
        if (isNaN(num)) {
            return "";
        }
        if (!num && num !== 0) {
            return "";
        }
        if (num && num <= 0) {
            return "";
        }
        if (num.toString().indexOf(".") > -1) {
            let intp = num.toString().split(".")[0];
            let pp = num.toString().split(".")[1];
            if (pp.length > n) {
                pp = pp.substr(0, n);
            }
            return (num = Number(intp + "." + pp));
        } else {
            return (num = Number(num));
        }
    },
    // 判断是否是0-100的非负整数
    checkNonInt(num) {
        let reg = new RegExp("^(\\d|[1-9]\\d|100)$");
        return reg.test(num);
    },
    // 判断是否是整数
    checkInt(val, n = 15) {
        let flag = isNaN("" + val);
        if (flag) {
            return false;
        }
        let str = "^\\d{1," + n + "}$";
        let reg = new RegExp(str);
        return reg.test(val);
    },
    // 判断是否只有n位小数
    checkFloatNeg(val, n = 2) {
        let flag = isNaN("" + val);
        if (flag) {
            return false;
        }
        let str = "^-?[0-9]+(.\\d{1," + n + "})?$";
        let reg = new RegExp(str);
        return reg.test(val);
    },

    /**-------------将对象转成路由字符串参数--------------**/
    createPath(url, params = {}) {
        let urlParams = [];
        Object.keys(params).forEach(key => {
            if (params[key] != "") {
                //判断参数不为空字符串
                urlParams.push(`${key}=${encodeURIComponent(params[key])}`);
            }
        });
        if (urlParams.length) {
            urlParams = `${url}?${urlParams.join("&")}`;
        } else {
            urlParams = url;
        }
        return urlParams;
    },
    /**-------------------- 数组去重 ----------------------**/
    distinctArray(arr, key) {
        let result = [];
        let obj = {};
        for (var i = 0; i < arr.length; i++) {
            if (!obj[arr[i][key]]) {
                result.push(arr[i]);
                obj[arr[i][key]] = true;
            }
        }
        return result;
    },
    // json数组根据某一元素判重
    arrCheckKey(arr, key) {
        // var arr = [{ d: '2015-10-12',C:'Apple'}, { d: '2015-10-12',C:'Apple'}, { d: '2015-10-13',C :'Apple' }];
        var find = false;
        for (var i = 0; i < arr.length; i++) {
            for (var j = i + 1; j < arr.length; j++) {
                if (arr[i][key] == arr[j][key]) {
                    find = true;
                    break;
                }
            }
            if (find) break;
        }
        return find;
    },
    // 手机号校验
    isPhoneAvailable(poneNum) {
        let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        if (!myreg.test(poneNum)) {
            return false;
        } else {
            return true;
        }
    },
    // 邮箱校验
    isEmailAvailable(email) {
        let myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
        if (!myreg.test(email)) {
            return false;
        } else {
            return true;
        }
    },
    //是否包含中文
    hasChinese(value) {
        let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g;
        let mat = value.match(cnReg);
        return mat;
    },
    /*--------------精确到小数点后两位,.后补0和.前补0-------------------------*/
    saveNumberTwo(num) {
        if ((!num && num != 0) || num == "") {
            return "";
        }
        if (!isNaN(num)) {
            num = parseFloat(num).toFixed(2);
        }
        num += "";
        num = num.replace(/[^0-9|\.]/g, ""); //清除字符串中的非数字非.字符

        if (/^0+/) {
            //清除字符串开头的0
            num = num.replace(/^0+/, "");
        }
        if (!/\./.test(num)) {
            //为整数字符串在末尾添加.00
            num += ".00";
        }
        if (/^\./.test(num)) {
            //字符以.开头时,在开头添加0
            num = "0" + num;
            num += "00"; //在字符串末尾补零
            num = num.match(/\d+\.\d{2}/)[0];
        }
        return num;
    },
    //校验是否为纯数字
    isNum(str) {
        if (/^[0-9]+$/.test(str)) {
            //这是用正则表达是检查
            return true;
        }
        return false;
    },
    // 判断字符串是否为数字和字母组合
    checkS(str) {
        var zg = /^[0-9a-zA-Z]*$/;
        if (!zg.test(str)) {
            return false;
        } else {
            return true;
        }
    },
    //对象深拷贝
    deepClone(source) {
        if (!source && typeof source !== "object") {
            throw new Error("error arguments", "shallowClone");
        }
        const targetObj = source.constructor === Array ? [] : {};
        Object.keys(source).forEach(keys => {
            if (source[keys] && typeof source[keys] === "object") {
                targetObj[keys] = deepClone(source[keys]);
            } else {
                targetObj[keys] = source[keys];
            }
        });
        return targetObj;
    },
    clearCookie() {
        var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
        if (keys) {
            for (var i = keys.length; i--;) document.cookie = keys[i] + "=0;expires=" + new Date(0).toUTCString();
        }
    },
    //清除所有cookie
    clearCookie() {
        var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
        if (keys) {
            for (var i = keys.length; i--;) document.cookie = keys[i] + "=0;expires=" + new Date(0).toUTCString();
        }
    },
    //电话号码脱敏 头三尾三，其余*
    phoneJoinStart(value) {
        let str = value + "",
            first = "",
            last = "",
            start = "";
        if (str.length < 6) return str;
        first = str.substr(0, 3);
        last = str.substr(-3);
        for (let i = 0; i < str.length - 6; i++) {
            start += "*";
        }
        return first + start + last;
    },
    //证件号脱敏 前五其余*
    pIdJoinStart(value) {
        let str = value + "",
            first = "",
            start = "";
        if (str.length < 6) return str;
        first = str.substr(0, 5);
        for (let i = 0; i < str.length - 5; i++) {
            start += "*";
        }
        return first + start;
    },
    //判断是不是图片文件
    isImg(value) {
        return /\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(value);
    },
    openLoading() {
        $loading = Loading.service({
            fullscreen: true,
            text: "加载中"
        });
    },
    closeLoading() {
        $loading ? $loading.close() : "";
    },
    //文件下载
    downloadEvt(src, target = true) {
        if (!src) return Message.error('下载地址为空!')
        let a = document.createElement('a');
        if (target)
            a.setAttribute('target', '_blank');
        a.href = src;
        a.download = target;
        const abox = document.body.appendChild(a);
        abox.click();
        document.body.removeChild(a);
    },
    // 下载文件流
    urlToBlob(theUrl, fileName, params, callback) {
        let date = moment(new Date()).format('YYYY-MM-DD')
        fileName = fileName + date + '.xls'
        let xhr = new XMLHttpRequest();
        let _this = this
        xhr.open("post", theUrl, true);
        xhr.setRequestHeader('x-store-token', getToken() || '');
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.responseType = "blob";
        xhr.onload = function () {
            console.log(this.response, fileName, 'fileName');
            if (this.status == 200)
                callback && callback(this.response, fileName) || _this.downloadXlsx(this.response, fileName)
        };
        xhr.send(JSON.stringify(params));
    },
    downloadXlsx(blob, name = "") {//下载 表格.xlsx
        if (!blob) return;
        var reader = new FileReader()
        reader.addEventListener('loadend', (e) => {
            console.log(blob, 'blob.type', e);
            // if(blob.type === 'application/json'){
            try {
                let { code, msg } = JSON.parse(e.target.result);
                Message.error(msg);
                return;
            } catch (error) {
                var downloadUrl = window.URL.createObjectURL(new Blob([blob]));//转换
                // 文件下载
                this.downloadEvt(downloadUrl, decodeURI(name), false)
            }
        })
        reader.readAsText(blob)
    },
    //导出文件
    exportFile(url, name, ids) {
        const now = new Date
        let year = now.getFullYear()
        let month = (now.getMonth() + 1) < 10 ? '0' + (now.getMonth() + 1) : (now.getMonth() + 1)
        let day = now.getDate() < 10 ? '0' + now.getDate() : now.getDate()
        // this.utils.downloadFile(res, 'cgh')
        this.urlToBlob2(that.$exportUlr + url, `${name}${year}${month}${day}.xls`, ids, this.downloadFile)
    },
    //导出文件
    urlToBlob2(theUrl, fileName, ids, callback) {
        let token = getToken() || ''
        let xhr = new XMLHttpRequest();
        let formData = new FormData()
        formData.append('ids', ids)
        // formData.append('ids',ids)
        xhr.open("post", theUrl, true);
        xhr.setRequestHeader("x-store-token", token);
        xhr.responseType = "blob";
        xhr.onload = function () {
            if (this.status == 200)
                callback && callback(this.response, fileName)
        };
        xhr.send(formData);
    },
    // 文件下载
    downloadFile(blobExample, fileName) {
        if (!blobExample) return
        let url = window.URL.createObjectURL(blobExample)
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click();
        document.body.removeChild(link)
    },
    //打印
    getPdf(domId, title, thas) {
        if (thas) thas.isPrint = true;
        console.log(thas, thas.isPrint);
        html2Canvas(document.getElementById(domId), {
            allowTaint: true,
            useCORS: true
        }).then(function (canvas) {
            let contentWidth = canvas.width
            let contentHeight = canvas.height
            let pageHeight = contentWidth / 592.28 * 841.89
            let leftHeight = contentHeight
            let position = 0
            let imgWidth = 595.28
            let imgHeight = 592.28 / contentWidth * contentHeight
            let pageData = canvas.toDataURL('image/jpeg', 1.0)
            let PDF = new JsPDF('', 'pt', 'a4')
            if (leftHeight < pageHeight) {
                PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
            } else {
                while (leftHeight > 0) {
                    PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                    leftHeight -= pageHeight
                    position -= 841.89
                    if (leftHeight > 0) {
                        PDF.addPage()
                    }
                }
            }
            PDF.save(title + '.pdf')
            setTimeout(() => {
                if (thas) thas.isPrint = false;
                console.log(thas, thas.isPrint, "@@@@@");
            });
        })
    },
    /*
    * 图片压缩
    * img    原始图片
    * width   压缩后的宽度
    * height  压缩后的高度
    * ratio   压缩比率
    */
    compress(file, width, height, ratio) {
        return new Promise(async (resolve, reject) => {
            var img = new Image();
            img.src = String(URL.createObjectURL(file));
            console.log(img.src, 'img.src');
            img.onload = () => {
                var canvas, ctx, img64;
                canvas = document.createElement('canvas');
                canvas.width = width;
                canvas.height = height;

                ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, width, height);

                img64 = canvas.toDataURL(file.type || "image/jpeg", ratio);
                resolve(this.base64ToBlob(img64));
            }
            img.onerror = (err) => {
                reject('图片加载失败' + err)
            }


        })
    },
    /**
    * @param {String} base64Data base64
    * @returns {Blob}
    * @description base64转blob
    */
    base64ToBlob(base64Data) {
        let arr = base64Data.split(',');
        if (arr[0]) {
            let fileType = arr[0].match(/:(.*?);/);

            let bstr = atob(arr[1]),
                l = bstr.length,
                u8Arr = new Uint8Array(l);

            while (l--) {
                u8Arr[l] = bstr.charCodeAt(l);
            }
            return new Blob([u8Arr], {
                type: fileType ? fileType[1] : ''
            });
        }
        return console.error(`canvas.toDataURL(file.type, qualityArgument) 转base64出错`);

    },
};